<template>
  <el-dialog :title="!dataForm.id ? '新增POS' : '修改POS'" :close-on-click-modal="false" :visible.sync="visible" class="add-or-update-el-dialog">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabs" :key="item.id" :label="item.name" :name="item.name" :id="item.id"></el-tab-pane>
    </el-tabs>
    <template>
      <el-row :gutter="10">
        <el-col :span="inputPriceFlag ? 6 : 24" style="border-right: 1px solid #ddd;">
          <div>
            <h4 style="text-align:center;font-size:24px">{{activeName}}</h4>
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
              <el-form-item prop="type" label="挂房账" style="margin-left: 0px;">
                <el-radio-group v-model="dataForm.type">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="courseId" size="small" label="消费类目" style="margin-bottom: 0px;">
                <el-select v-model="dataForm.courseId" @change="consumeChange" placeholder="请选择">
                  <el-option v-for="item in dataList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item size="small" :style="dataList.filter(item=>item.isQuick == 1).length == 0 ? '' : 'margin-bottom: 2px;'">
                <el-link style="margin-right: 5px;" v-for="item in dataList.filter(item=>item.isQuick == 1)" :key="item.id"
                  @click="linkClick(item)" type="primary">{{item.name}}</el-link>
              </el-form-item>

              <el-form-item label="消费金额" prop="consumeMoney">
                <el-input v-model="dataForm.consumeMoney" :disabled="inputPriceFlag" placeholder="金额"></el-input>
              </el-form-item>
              <!--              <el-form-item size="small" label="付款方式" v-if="dataForm.type==0">
                <el-select v-model="dataForm.payTypeId" placeholder="请选择">
                  <el-option v-for="item in options.paysTypeOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付款金额" v-if="dataForm.type==0">
                <el-tag type="danger">{{dataForm.payMoney}}</el-tag>
              </el-form-item> -->

              <el-form-item label="入账人" v-if="dataForm.type==1">
                <el-autocomplete v-model="dataForm.sa" style="width: 100%;" :fetch-suggestions="querySearchAsync"
                  placeholder="请输入内容" @select="handleSelect"></el-autocomplete>

                <!--                <el-select
                  v-model="dataForm.peopleId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options.peopleOptions"
                    :key="item.name"
                    :label="item.hotelFloorRoomEntity.roomSign+item.hotelFloorRoomEntity.roomNum + '-' + item.name"
                    :value="item.id"
                  ></el-option> -->
                </el-select>
              </el-form-item>

              <el-form-item label="备注">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="dataForm.note">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="dataFormSubmit()">{{dataForm.type == 1 ? '提交' : '保存'}}</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="18" v-if="inputPriceFlag">
          <div>
            <el-form :inline="true" :model="dataForm">
              <el-form-item>
                <el-select v-model="dataForm.consumeId2" @change="getShopDataList" placeholder="类别" clearable>
                  <el-option v-for="item in consumeEntities" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input v-model="dataForm.key" placeholder="名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button icon="el-icon-search" circle @click="getShopDataList"></el-button>
              </el-form-item>
            </el-form>
            <el-table :data="shopDataList" v-loading="shopDataListLoading" style="width: 100%;">
              <el-table-column prop="shopName" header-align="center" align="center" label="名称"></el-table-column>
              <el-table-column prop="salePrice" header-align="center" align="center" label="售价">
                <template slot-scope="scope">
                  <el-input-number size="mini" @change="shopChange()" v-model="scope.row.salePrice" :precision="2"
                    :step="1" :min="0"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="count" header-align="center" align="center" label="数量">
                <template slot-scope="scope">
                  <el-input-number size="mini" @change="shopChange()" v-model="scope.row.count" :step="1" :min="0" :max="scope.row.stockNum"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="stockNum" header-align="center" align="center" label="剩余库存">
                <template slot-scope="scope">
                  {{ scope.row.stockNum - scope.row.count }}
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
          </div>
        </el-col>
      </el-row>
    </template>
    <!-- <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span> -->
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        inputPriceFlag: true,
        visible: false,
        dataForm: {
          id: 0,
          key:'',
          sellerId: '',
          consumelist: '',
          consumeId2: '',
          courseId: '-1',
          courseInfo: '',
          billNo: '',
          projectId: '',
          type: 0,
          peopleId: '',
          consumeMoney: 0,
          payTypeId: '',
          payMoney: 0,
          note: '',
          createTime: '',
          updateTime: '',
          state: 1,
          sa: '',
          pfno: '',
          fname: '',
          ftel: '',
          sdjdh: '',
          fjr: ''
        },
        dataList: [],
        restaurants: [],
        dataRule: {
          sellerId: [{
            required: true,
            message: '酒店Id不能为空',
            trigger: 'blur'
          }],
          courseId: [{
            required: true,
            message: '科目Id不能为空',
            trigger: 'blur'
          }],
          courseInfo: [{
            required: true,
            message: '科目消费具体信息不能为空',
            trigger: 'blur'
          }],
          billNo: [{
            required: true,
            message: '单号不能为空',
            trigger: 'blur'
          }],
          projectId: [{
            required: true,
            message: '地点Id不能为空',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '1挂房账，0现付账不能为空',
            trigger: 'blur'
          }],
          peopleId: [{
            required: true,
            message: '挂房账时peopleId不能为空',
            trigger: 'blur'
          }],
          consumeMoney: [{
            required: true,
            message: '消费金额不能为空',
            trigger: 'blur'
          }],
          payTypeId: [{
            required: true,
            message: '付款方式ID不能为空',
            trigger: 'blur'
          }],
          payMoney: [{
            required: true,
            message: '付款金额不能为空',
            trigger: 'blur'
          }],
          note: [{
            required: true,
            message: '备注不能为空',
            trigger: 'blur'
          }],
          createTime: [{
            required: true,
            message: '创建时间不能为空',
            trigger: 'blur'
          }],
          updateTime: [{
            required: true,
            message: '修改时间不能为空',
            trigger: 'blur'
          }],
          state: [{
            required: true,
            message: '状态 0未结账，1已结账不能为空',
            trigger: 'blur'
          }]
        },
        showcount: 0,
        activeName: '', //tab被选中的名字
        activeTab: {}, //被选中的tab对象
        tabs: [], //加载的tabs project表
        courses: [], //消费科目
        shopForm: {
          shopNumber: '',
          shopName: ''
        },
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        shopDataList: [], //商品信息
        shopDataListLoading: false,
        options: { //支付选项
          paysTypeOptions: [],
          peopleOptions: []
        },
        goods: [],

      }
    },
    created() {
      this.getList();
    },
    methods: {

		  linkClick(item){
		    this.dataForm.courseId = item.id
		    this.consumeChange()
		  },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getShopDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getShopDataList();
      },
      handleSelect(item) {
        this.dataForm.fjr = item.id;
        var name = item.value;
        var tel = item.label;
        var names = name.split("/");
        var tels = tel.split("/");
        this.dataForm.pfno = names[0];
        this.dataForm.fname = names[1];
        this.dataForm.ftel = tels[1];
        this.dataForm.sdjdh = tels[0];

      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
        clearTimeout(this.timeout);
        cb(results);
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      getList() {
        var type = '2';
        this.$http({
          url: this.$http.adornUrl('/hotel/trentalgoods/selectroomplist/' + type),
          method: 'post',
        }).then(({
          data
        }) => {
          this.restaurants = data.page;
        });
      },
      initData() {
        this.activeName = '', //tab被选中的名字
          this.activeTab = {}, //被选中的tab对象
          this.tabs = [], //加载的tabs project表
          this.courses = [], //消费科目
          this.shopForm = {
            shopNumber: '',
            shopName: ''
          },
          this.shopDataList = [], //商品信息
          this.shopDataListLoading = false,
          this.options = { //支付选项
            paysTypeOptions: [],
            peopleOptions: []
          },
          this.goods = [],
          this.dataForm.note = '',
          this.dataForm.consumeMoney = 0,
          this.dataForm.payMoney = 0
      },
      init(id) {
        this.getList();
        this.getDataList();
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.initData()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/hotel/thotelcashbills/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.dataForm.sellerId = data.tHotelCashBills.sellerId
                this.dataForm.courseId = data.tHotelCashBills.courseId
                this.dataForm.courseInfo = data.tHotelCashBills.courseInfo
                this.dataForm.billNo = data.tHotelCashBills.billNo
                this.dataForm.projectId = data.tHotelCashBills.projectId
                this.dataForm.type = data.tHotelCashBills.type
                this.dataForm.peopleId = data.tHotelCashBills.peopleId
                this.dataForm.consumeMoney = data.tHotelCashBills.consumeMoney
                this.dataForm.payTypeId = data.tHotelCashBills.payTypeId
                this.dataForm.payMoney = data.tHotelCashBills.payMoney
                this.dataForm.note = data.tHotelCashBills.note
                this.dataForm.createTime = data.tHotelCashBills.createTime
                this.dataForm.updateTime = data.tHotelCashBills.updateTime
                this.dataForm.state = data.tHotelCashBills.state
                this.activeTab = data.tab
                this.activeName = this.activeTab.name
                this.goods = data.goods
                this.consumeChange();


              }
            })
          }
          this.loadTabs();
          this.loadCourses(); //获取商品种类
          this.getPayTypes(); //获取支付方式
          this.getPeopls(); //获取入账人
        })
      },
      // 表单提交
      dataFormSubmit() {
        if (this.dataForm.courseId == '-1') {
          if (this.showcount <= 0) {
            this.$message.error("请选择右边类型");
            return false
          }

        }
        if (this.dataForm.consumeMoney <= 0) {
          this.$message.error("没有消费")
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/hotel/thotelcashbills/${!this.dataForm.id ? 'saveAll' : 'setUpdateAll'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'sellerId': this.dataForm.sellerId,
                'courseId': this.dataForm.courseId,
                'projectId': this.activeTab.id, //对应地点ID
                'courseInfo': this.dataForm.courseInfo,
                'billNo': this.dataForm.billNo,
                'type': this.dataForm.type,
                'peopleId': this.dataForm.peopleId,
                'consumeMoney': this.dataForm.consumeMoney,
                'payTypeId': this.dataForm.payTypeId,
                'fjr': this.dataForm.fjr,
                'payMoney': this.dataForm.payMoney,
                'note': this.dataForm.note,
                'createTime': this.dataForm.createTime,
                'updateTime': this.dataForm.updateTime,
                'state': 1,
                sign: JSON.stringify(this.shopDataList.filter(item => item.count > 0)),
                'goods': this.goods
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                    if (this.dataForm.type == 0) {
                      this.$parent.checkOutBillsHandle(data.id);
                    }
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      loadTabs() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelcashbillsproject/listByState'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 999,
            'state': 1
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.tabs = data.page.list
            this.activeName = this.tabs[0].name
            this.activeTab = this.tabs[0]
          } else {
            this.tabs = []
          }
        })
      },
      loadCourses() {
        this.courses = [];
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroomconsume/data'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            var map = {};
            map["label"] = "全部";
            map["value"] = "-1";
            this.courses.push(map);
            this.courses = this.courses.concat(data.data);
            console.log(this.courses);
            this.getShopDataList();
          } else {
            this.courses = [];
          }
        });
      },
      consumeChange() {
        this.dataForm.consumeId2 = '';
        this.shopDataList = []
        //请求旗下分类
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroomconsume/subsetList'),
          method: 'get',
          params: this.$http.adornParams({
            parentId:this.dataForm.courseId,
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.consumeEntities = data.consumeEntities
          }
        });
        this.getShopDataList();
      },
      shopChange() {
        this.showcount = 0;
        //计算价格
        this.goods = [];
        var money = 0;
        this.shopDataList.forEach(item => {
          var count = item.count;
          this.showcount += count;
          var salePrice = item.salePrice;
          money += count * salePrice;

          if (item.count > 0) {
            var temp = {}
            temp.goodsId = item.id
            temp.number = item.count
            temp.name = item.shopName
            temp.djmoney = item.salePrice
            temp.printId = item.parentId
            this.goods.push(temp)
          }
        });
        this.dataForm.consumeMoney = money;
        this.dataForm.payMoney = money;
      },
      goodsUpdate() {
        this.goods.forEach(item1 => {
          console.log("item1", item1)
          this.shopDataList.forEach(item => {
            console.log("item1.goodsId", item1.goodsId)
            console.log("item.id", item.id)
            if (item1.goodsId == item.id) {
              item.count = item1.number
            }
          });
        });
      },
      // 获取商品列表
      getShopDataList() {
        this.dataListLoading = true;
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroomconsumeshop/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: this.pageIndex,
            limit: this.pageSize,
            parentId:this.dataForm.consumeId2 ? this.dataForm.consumeId2 : this.dataForm.courseId,
            state: 1,
            key: this.dataForm.key
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.shopDataList = data.page.list.map(item => ({
              ...item,
              count: 0
            }));
              this.totalPage = data.page.totalCount;
              if (this.totalPage > 0) {
                this.inputPriceFlag = true;
              } else {
                this.inputPriceFlag = false;
              }
          } else {
            this.shopDataList = [];
          }
          this.dataListLoading = false;
        });
      },
      //获取支付方式
      getPayTypes() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroompaytype/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: 1,
            limit: 999
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.options.paysTypeOptions = data.page.list;
            this.dataForm.payTypeId = this.options.paysTypeOptions[0].id;
          } else {
            this.options.paysTypeOptions = [];
          }
        });
      },
	  // 获取数据列表
	  getDataList() {
	    this.$http({
	      url: this.$http.adornUrl('/hotel/thotelfloorroomconsume/list'),
	      method: 'get',
	      params: this.$http.adornParams({
	        page: 1,
	        limit: 999,
	        parentId: 0
	      })
	    }).then(({
	      data
	    }) => {
	      if (data && data.code === 0) {
	        this.dataList = data.page.list;
          //默认选中第一个
          this.dataForm.courseId = this.dataList[0].id
          this.consumeChange();
	        console.log(this.dataList);
	      } else {
	        this.dataList = [];
	      }
	    });
	  },
      //获取入账账号
      getPeopls() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinsingle/guest_list`),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 999,
            'state': 1
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log("入账：", data)
            this.options.peopleOptions = data.data.page.list;
            this.dataForm.peopleId = this.options.peopleOptions[0].id;
          } else {
            this.options.peopleOptions = [];
          }
        });
      },
      handleClick(val) {
        //tab点击监听
        this.activeTab = this.tabs[val.index]
        // console.log("tabname:", this.activeTab)
      }
    }
  }
</script>

<style lang="scss" scoped>
  @media only screen and (max-width: 1380px) {
    .el-dialog__wrapper /deep/ .el-dialog {
      width: 80%;
    }
  }
</style>
